package it.xiuxian.homepage.activity

import android.os.Build
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bytedance.sdk.openadsdk.*
import com.othershe.calendarview.listener.OnPagerChangeListener
import com.othershe.calendarview.listener.OnSingleChooseListener
import com.othershe.calendarview.utils.CalendarUtil
import com.zzhoujay.richtext.RichText
import it.xiuxian.homepage.R
import it.xiuxian.homepage.bean.QianDaoBean
import it.xiuxian.homepage.bean.WorkBean
import it.xiuxian.homepage.databinding.HomepageQiandaoBinding
import it.xiuxian.homepage.presenter.QianDaoActivityPresenter
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseActivity
import it.xiuxian.lib.bean.NewPersonBean
import it.xiuxian.lib.utils.*

@Route(path = ArouterAddress.QIANDAOACTIVITY)
class QianDaoActivity:BaseActivity<QianDaoActivityPresenter>(){
   lateinit var binding:HomepageQiandaoBinding
    private val cDate = CalendarUtil.getCurrentDate()
    fun updateUI(msg: String) {
        ToastUtil.showShort(msg)
        mPresenter!!.getlist("1")
        mPresenter!!.getHomePage()
    }

    override val layoutId: Int
        get() = R.layout.homepage_qiandao
    override val presenter: QianDaoActivityPresenter
        get() = QianDaoActivityPresenter()

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView(){
        binding = getViewDataBinding<HomepageQiandaoBinding>()
        setTitle("每日签到")

        binding.tvQiandao.setOnClickListener {
            if(Utils.isFastClick()){
                initGuanggao()
            }

        }
        binding.tvLingqu.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.WORKACTIVITY).navigation()
        }
        binding.tvLingqu1.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.WORKACTIVITY).navigation()
        }
        binding.llQian.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.QIANDAORECORDACTIVITY).navigation()
        }

    }

    override fun initData(){
       // super.initData()
        mPresenter!!.getlist("1")
        mPresenter!!.getHomePage()
    }
        private var mTTAdNative: TTAdNative? = null
        private var mHorizontalCodeId: String? = null
        private var mVerticalCodeId: String? = null
        private var mIsExpress = false //是否请求模板广告
        private  val TAG = "HomePageFragment"
        private var mIsLoaded = false //视频是否加载完成
        private var mttRewardVideoAd: TTRewardVideoAd? = null
        private var mHasShowDownloadActive = false
        fun initGuanggao(){
            //step1:初始化sdk
            val ttAdManager = TTAdManagerHolder.get()
            //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
            //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
            TTAdManagerHolder.get().requestPermissionIfNecessary(this)
            //step3:创建TTAdNative对象,用于调用广告请求接口

            //step3:创建TTAdNative对象,用于调用广告请求接口
            mTTAdNative = ttAdManager.createAdNative(this.applicationContext)
            getExtraInfo()
        }
        private fun getExtraInfo(){
            val intent = this.intent?: return
            mHorizontalCodeId = intent.getStringExtra("horizontal_rit")
            mVerticalCodeId = intent.getStringExtra("vertical_rit")
            mIsExpress = intent.getBooleanExtra("is_express", false)
            loadAd("947626021", TTAdConstant.VERTICAL)
        }
        fun showAd(){
            if (mttRewardVideoAd != null) {
                //step6:在获取到广告后展示,强烈建议在onRewardVideoCached回调后，展示广告，提升播放体验
                //该方法直接展示广告
//                    mttRewardVideoAd.showRewardVideoAd(RewardVideoActivity.this);

                //展示广告，并传入广告展示的场景
                mttRewardVideoAd!!.showRewardVideoAd(
                    this,
                    TTAdConstant.RitScenes.CUSTOMIZE_SCENES,
                    "scenes_test"
                )
                mttRewardVideoAd = null
            } else {
               // TToast.show(this, "请先加载广告")
            }
        }
        private fun loadAd(mVerticalCodeId: String?, vertical: Int){
            //step4:创建广告请求参数AdSlot, 具体参数含义参考文档


            //step4:创建广告请求参数AdSlot,具体参数含义参考文档
            val adSlot: AdSlot
            adSlot = if (mIsExpress) {
                //个性化模板广告需要传入期望广告view的宽、高，单位dp，
                AdSlot.Builder()
                    .setCodeId(mVerticalCodeId) //此次加载广告的用途是实时加载，当用来作为缓存时，请使用：TTAdLoadType.LOAD
                    .setAdLoadType(TTAdLoadType.LOAD) //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
                    .setExpressViewAcceptedSize(500f, 500f)
                    .build()
            } else {
                //模板广告需要设置期望个性化模板广告的大小,单位dp,代码位是否属于个性化模板广告，请在穿山甲平台查看
                AdSlot.Builder() //此次加载广告的用途是实时加载，当用来作为缓存时，请使用：TTAdLoadType.LOAD
                    .setAdLoadType(TTAdLoadType.LOAD)
                    .setCodeId(mVerticalCodeId)
                    .build()
            }
            //step5:请求广告

            //step5:请求广告
            mTTAdNative!!.loadRewardVideoAd(adSlot, object : TTAdNative.RewardVideoAdListener {
                override fun onError(code: Int, message: String) {
                    Log.e(
                        TAG,
                        "Callback --> onError: $code, $message"
                    )
                  //  TToast.show(this, message)
                }

                //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
                override fun onRewardVideoCached() {
                    Log.e(
                        TAG,
                        "Callback --> onRewardVideoCached"
                    )
                    mIsLoaded = true
                  //  TToast.show(this, "Callback --> rewardVideoAd video cached")
                }

                override fun onRewardVideoCached(ad: TTRewardVideoAd) {
                    Log.e(
                        TAG,
                        "Callback --> onRewardVideoCached"
                    )
                    mIsLoaded = true
                  //  TToast.show(this, "Callback --> rewardVideoAd video cached")
                    showAd()
                    // ad.showRewardVideoAd(RewardVideoActivity.this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
                }

                //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
                override fun onRewardVideoAdLoad(ad: TTRewardVideoAd) {
                    Log.e(
                        TAG,
                        "Callback --> onRewardVideoAdLoad"
                    )
                    /*  TToast.show(
                        this,
                        "rewardVideoAd loaded 广告类型：" + getAdType(ad.rewardVideoAdType)
                    )*/
                    mIsLoaded = false
                    mttRewardVideoAd = ad
                    mttRewardVideoAd!!.setRewardAdInteractionListener(object :
                        TTRewardVideoAd.RewardAdInteractionListener {
                        override fun onAdShow() {
                            Log.d(
                                TAG,
                                "Callback --> rewardVideoAd show"
                            )
                          //  TToast.show(this, "rewardVideoAd show")
                        }

                        override fun onAdVideoBarClick(){
                            Log.d(
                                TAG,
                                "Callback --> rewardVideoAd bar click"
                            )
                          //  TToast.show(this, "rewardVideoAd bar click")
                        }

                        override fun onAdClose() {
                            Log.d(
                                TAG,
                                "Callback --> rewardVideoAd close"
                            )
                         //   TToast.show(this, "rewardVideoAd close")
                        }

                        //视频播放完成回调
                        override fun onVideoComplete() {
                            Log.d(
                                TAG,
                                "Callback --> rewardVideoAd complete"
                            )
                         //  TToast.show(this, "rewardVideoAd complete")
                        }

                        override fun onVideoError() {
                            Log.e(
                                TAG,
                                "Callback --> rewardVideoAd error"
                            )
                           // TToast.show(this, "rewardVideoAd error")
                        }

                        //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                        override fun onRewardVerify(
                            rewardVerify: Boolean,
                            rewardAmount: Int,
                            rewardName: String,
                            errorCode: Int,
                            errorMsg: String
                        ) {
                            if(rewardVerify){
                                mPresenter!!.qiandao()
                            }
                            /* val logString = "verify:" + rewardVerify + " amount:" + rewardAmount +
                                     " name:" + rewardName + " errorCode:" + errorCode + " errorMsg:" + errorMsg
                             Log.e(
                                 TAG,
                                 "Callback --> $logString"
                             )
                             TToast.show(this, logString)*/
                        }

                        override fun onSkippedVideo(){
                            Log.e(
                                TAG,
                                "Callback --> rewardVideoAd has onSkippedVideo"
                            )
                        //    TToast.show(this, "rewardVideoAd has onSkippedVideo")
                        }
                    })
                    mttRewardVideoAd!!.setRewardPlayAgainInteractionListener(object :
                        TTRewardVideoAd.RewardAdInteractionListener {
                        override fun onAdShow(){
                            Log.d(
                                TAG,
                                "Callback --> rewardPlayAgain show"
                            )
                         //   TToast.show(this, "rewardVideoAd show")
                        }

                        override fun onAdVideoBarClick() {
                            Log.d(
                                TAG,
                                "Callback --> rewardPlayAgain bar click"
                            )
                        //    TToast.show(this, "rewardVideoAd bar click")
                        }

                        override fun onAdClose() {
                            Log.d(
                                TAG,
                                "Callback --> rewardPlayAgain close"
                            )
                         //   TToast.show(this, "rewardVideoAd close")
                        }

                        //视频播放完成回调
                        override fun onVideoComplete() {
                            Log.d(
                                TAG,
                                "Callback --> rewardPlayAgain complete"
                            )
                         //   TToast.show(this, "rewardVideoAd complete")
                        }

                        override fun onVideoError() {
                            Log.e(
                                TAG,
                                "Callback --> rewardPlayAgain error"
                            )
                          //  TToast.show(this, "rewardVideoAd error")
                        }

                        //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                        override fun onRewardVerify(
                            rewardVerify: Boolean,
                            rewardAmount: Int,
                            rewardName: String,
                            errorCode: Int,
                            errorMsg: String
                        ) {
                            val logString =
                                "rewardPlayAgain verify:" + rewardVerify + " amount:" + rewardAmount +
                                        " name:" + rewardName + " errorCode:" + errorCode + " errorMsg:" + errorMsg
                            Log.e(
                                TAG,
                                "Callback --> $logString"
                            )
                           // TToast.show(this, logString)
                        }

                        override fun onSkippedVideo() {
                            Log.e(
                                TAG,
                                "Callback --> rewardPlayAgain has onSkippedVideo"
                            )
                           // TToast.show(this, "rewardVideoAd has onSkippedVideo")
                        }
                    })
                    mttRewardVideoAd!!.setDownloadListener(object : TTAppDownloadListener{
                        override fun onIdle(){
                            mHasShowDownloadActive = false
                        }

                        override fun onDownloadActive(
                            totalBytes: Long,
                            currBytes: Long,
                            fileName: String,
                            appName: String
                        ){
                            Log.d(
                                "DML",
                                "onDownloadActive==totalBytes=$totalBytes,currBytes=$currBytes,fileName=$fileName,appName=$appName"
                            )
                            if (!mHasShowDownloadActive) {
                                mHasShowDownloadActive = true
                               // TToast.show(this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG)
                            }
                        }

                        override fun onDownloadPaused(
                            totalBytes: Long,
                            currBytes: Long,
                            fileName: String,
                            appName: String
                        ) {
                            Log.d(
                                "DML",
                                "onDownloadPaused===totalBytes=$totalBytes,currBytes=$currBytes,fileName=$fileName,appName=$appName"
                            )
                          //  TToast.show(this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG)
                        }

                        override fun onDownloadFailed(
                            totalBytes: Long,
                            currBytes: Long,
                            fileName: String,
                            appName: String
                        ) {
                            Log.d(
                                "DML",
                                "onDownloadFailed==totalBytes=$totalBytes,currBytes=$currBytes,fileName=$fileName,appName=$appName"
                            )
                            //TToast.show(this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG)
                        }

                        override fun onDownloadFinished(
                            totalBytes: Long,
                            fileName: String,
                            appName: String
                        ) {
                            Log.d(
                                "DML",
                                "onDownloadFinished==totalBytes=$totalBytes,fileName=$fileName,appName=$appName"
                            )
                            //TToast.show(this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG)
                        }

                        override fun onInstalled(fileName: String, appName: String) {
                            Log.d("DML", "onInstalled==,fileName=$fileName,appName=$appName")
                           // TToast.show(this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG)
                        }
                    })
                }
            })
        }

    fun getXinXI(data: NewPersonBean){
        if(data.qiandaostate=="1"){
            binding.tvQiandao.setText("已签到")
            binding.tvQiandao.isClickable =false
            binding.tvQiandao.isEnabled =false
            LiveDataBus.get().with(RxBusCode.QIANDAO).postValue(1980)
        }else{
            binding.tvQiandao.setText("签到领取")
            binding.tvQiandao.isClickable =true
            binding.tvQiandao.isEnabled =true
        }
      //  binding.tvGongnum.setText(data.)


    }

    fun setUI(data: WorkBean){
        Log.e("data",data.toString())
        binding.tvGongxian.setText(data.qiandaogongxianzhi+"贡献值")
        binding.tv1.setText("累计签到"+data.monthnum+"天")
        binding.tvGongnum.setText(data.qiandaojiangli+"个贡献值")
        RichText.from(data.huodongguize).into(binding.tvgui1)
       // binding.tvgui1.setText(data.huodongguize)
       // binding.tvgui2.setText("2、每月打卡总数为"+data.leijiqiandaonum+"天以上，既可以额外多获得"+data.leijiqiandaojiangli+"贡献值全勤奖。")

    }
}
